package com.infodeli.common.utils;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Map;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.http.HttpServletRequest;

public class JWTUtils {

    private static final String SIGN = "JJKKLL";
    /**
     * 生成token：header、payload、sign
     * @param map
     * @return
     */
    public static String getToken(Map<String,String> map) throws UnsupportedEncodingException {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v)->{
            builder.withClaim(k, v);
        });
        String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SIGN));
        return token;
    }

    public static void verify(String token) throws UnsupportedEncodingException {
        JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    public static DecodedJWT getTokenInfo(String token) throws UnsupportedEncodingException {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        return verify;
    }

    public static String getTokenInfo(String token, String key) throws UnsupportedEncodingException {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        return verify.getClaim(key).asString();
    }

    // 本来想着方便，但是又觉得 他应该仅知道他应该知道的东西
    //public static String getTokenInfo(HttpServletRequest request, String key) throws UnsupportedEncodingException {
    //    String token = request.getHeader("token");
    //    DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    //    return verify.getClaim(key).asString();
    //}



}
